package com;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class LogoutListener implements HttpSessionListener {
    public static final Logger LOG = LoggerFactory.getLogger(LogoutListener.class);

    public LogoutListener() {
    }

    public void sessionCreated(HttpSessionEvent arg0) {
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {

        HttpSession session = arg0.getSession();
        String name = (String) session.getAttribute("nickname");
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());

        LogoutExecutor logoutExecutor = (LogoutExecutor) context.getBean("logoutExecutor");

        logoutExecutor.logout(name);

        LOG.info("Logged out with name: " + name);
    }


}
